import {observable, computed, action} from 'mobx'
import {StoreBase} from "@/stores";

/**
 * 表单存储
 */
export class FormStore extends StoreBase {

    @observable _errorCount = 0
    @observable _validatingCount = 0


    @computed get hasValidating() {
        return this._validatingCount > 0
    }

    @computed get hasErrors() {
        return this._errorCount > 0
    }

    @action validate() {
        this._errorCount = 0
        this._validatingCount = 0
        this.children.forEach(fieldStore => {
            fieldStore.validate()
        })
    }

    getModel() {
        const values = Array.from(this.children.values())
        const model = values.reduce((before, current) => {
            return {
                ...before,
                ...{[current.name]: current.computedValue || current.value || ''}
            }
        }, {})
        return model
    }

    @action setModel(model) {
        if (model) {
            for (let name in model) {
                const store = this.get(name)
                if (store) {
                    store.changeValue(model[name])
                } else {
                    console.warn(`设置属性[value]失败,找不到属性[${name}]`)
                }
            }
        }
    }

    @action errorIncrease() {
        this._errorCount++
    }

    @action errorDecrease() {
        if (this._errorCount > 0)
            this._errorCount--
    }


    @action validatingIncrease() {
        this._validatingCount++
    }


    @action validatingDecrease() {
        if (this._validatingCount > 0)
            this._validatingCount--
    }
}

